<template>
  <div class="sales-data-page">
    <div class="page-header">
      <h2>销售数据分析</h2>
      <div class="header-actions">
        <Button type="primary" @click="handleExport">导出数据</Button>
        <Button @click="handleBack">返回</Button>
      </div>
    </div>

    <Card title="数据筛选" :bordered="false" class="search-card">
      <Form layout="inline">
        <Row :gutter="16">
          <Col :span="8">
            <FormItem label="地域">
              <Select v-model:value="queryParams.region" placeholder="请选择" allowClear style="width: 100%">
                <SelectOption v-for="item in regionList" :key="item" :value="item">{{ item }}</SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem label="档位">
              <Select v-model:value="queryParams.grade" placeholder="请选择" allowClear style="width: 100%">
                <SelectOption v-for="item in gradeList" :key="item" :value="item">{{ item }}</SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem label="品牌">
              <Select v-model:value="queryParams.brand" placeholder="请选择" allowClear style="width: 100%">
                <SelectOption v-for="item in brandList" :key="item" :value="item">{{ item }}</SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem label="种类">
              <Select v-model:value="queryParams.category" placeholder="请选择" allowClear style="width: 100%">
                <SelectOption v-for="item in categoryList" :key="item" :value="item">{{ item }}</SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem label="商品名称">
              <Select 
                v-model:value="queryParams.productName" 
                placeholder="请输入" 
                allowClear 
                showSearch
                :filter-option="false"
                @search="handleProductSearch"
                style="width: 100%"
              >
                <SelectOption v-for="item in productList" :key="item" :value="item">{{ item }}</SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem>
              <Space>
                <Button type="primary" @click="handleSearch">查询</Button>
                <Button @click="handleReset">重置</Button>
              </Space>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Card>

    <Card :bordered="false" class="table-card">
      <Table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="false"
        :row-key="(_record: any, index?: number) => index || 0"
        :scroll="{ x: 1500 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'tradePrice'">
            <span style="color: #1890ff">¥{{ formatMoney(record['订货价']) }}</span>
          </template>
          <template v-if="column.key === 'retailPrice'">
            <span style="color: #1890ff">¥{{ formatMoney(record['销售价']) }}</span>
          </template>
          <template v-if="column.key === 'sales2022'">
            <span style="color: #52c41a; font-weight: 600">{{ formatNumber(record['2022_全年_实销(条)']) }}条</span>
          </template>
          <template v-if="column.key === 'sales2023'">
            <span style="color: #52c41a; font-weight: 600">{{ formatNumber(record['2023_全年_实销(条)']) }}条</span>
          </template>
          <template v-if="column.key === 'sales2024'">
            <span style="color: #52c41a; font-weight: 600">{{ formatNumber(record['2024_全年_实销(条)']) }}条</span>
          </template>
        </template>
      </Table>

      <Pagination
        v-show="total > 0"
        :total="total"
        :current="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        show-size-changer
        :show-total="(total: number) => `共 ${total} 条`"
        @change="handlePageChange"
        @showSizeChange="handlePageSizeChange"
        style="margin-top: 16px; text-align: right"
      />
    </Card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { 
  Card, 
  Form, 
  FormItem, 
  Row, 
  Col, 
  Select, 
  SelectOption, 
  Button, 
  Space, 
  Table,
  Pagination,
  message 
} from 'ant-design-vue';
import { getSalesDataList, getSalesDataOptions, searchProducts, exportSalesData } from '#/api/operate/demand';

const router = useRouter();

const regionList = ref<string[]>([]);
const gradeList = ref<string[]>([]);
const brandList = ref<string[]>([]);
const categoryList = ref<string[]>([]);
const productList = ref<string[]>([]);

const dataSource = ref<any[]>([]); // 当前页显示的数据
const allDataList = ref<any[]>([]); // 存储所有数据
const loading = ref(false);
const total = ref(0);

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  region: undefined,
  grade: undefined,
  brand: undefined,
  category: undefined,
  productName: undefined
});

const columns: any[] = [
  { title: '地域', dataIndex: '地域', key: 'region', width: 120, fixed: 'left' as const },
  { title: '档位', dataIndex: '档位', key: 'grade', width: 80 },
  { title: '品牌', dataIndex: '品牌', key: 'brand', width: 120 },
  { title: '种类', dataIndex: '种类', key: 'category', width: 100 },
  { title: '商品编码', dataIndex: '商品编码', key: 'code', width: 120 },
  { title: '商品名称', dataIndex: '商品名称', key: 'name', width: 200, ellipsis: true },
  { title: '订货价', dataIndex: '订货价', key: 'tradePrice', width: 100, align: 'right' as const },
  { title: '销售价', dataIndex: '销售价', key: 'retailPrice', width: 100, align: 'right' as const },
  { title: '2022年实销', dataIndex: '2022_全年_实销(条)', key: 'sales2022', width: 150, align: 'right' as const },
  { title: '2023年实销', dataIndex: '2023_全年_实销(条)', key: 'sales2023', width: 150, align: 'right' as const },
  { title: '2024年实销', dataIndex: '2024_全年_实销(条)', key: 'sales2024', width: 150, align: 'right' as const }
];

const formatMoney = (val: any) => {
  if (!val) return '0.00';
  return Number(val).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

const formatNumber = (val: any) => {
  if (!val) return '0';
  return Number(val).toLocaleString('zh-CN');
};

const loadOptions = async () => {
  try {
    const res = await getSalesDataOptions();
    const data = res.data || {};
    regionList.value = data.regions || [];
    gradeList.value = data.grades || [];
    brandList.value = data.brands || [];
    categoryList.value = data.categories || [];
  } catch (error) {
    console.error('加载选项失败', error);
  }
};

const handleProductSearch = async (keyword: string) => {
  if (!keyword) {
    productList.value = [];
    return;
  }
  try {
    const res = await searchProducts(keyword);
    productList.value = res.data || [];
  } catch (error) {
    console.error('搜索商品失败', error);
  }
};

/** 查询数据列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await getSalesDataList(queryParams.value);
    console.log('API 返回数据:', res);
    
    // 根据后端实际返回的数据结构处理
    if (Array.isArray(res)) {
      // 如果直接返回数组
      allDataList.value = res;
      total.value = res.length;
    } else if (res && Array.isArray(res.data)) {
      // 如果返回的是 { data: [...] } 结构
      allDataList.value = res.data;
      total.value = res.data.length;
    } else if (res && Array.isArray(res.rows)) {
      // 如果返回的是 { rows: [...], total: number } 结构
      allDataList.value = res.rows;
      total.value = res.total || res.rows.length;
    } else {
      console.warn('未知的数据结构:', res);
      allDataList.value = [];
      total.value = 0;
    }
    
    // 客户端分页
    updateTableList();
    
    console.log('处理后的表格数据:', dataSource.value);
    console.log('数据总数:', total.value);
  } catch (error) {
    console.error('获取数据失败:', error);
    allDataList.value = [];
    dataSource.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

/** 更新表格显示数据(客户端分页) */
const updateTableList = () => {
  const startIndex = (queryParams.value.pageNum - 1) * queryParams.value.pageSize;
  const endIndex = startIndex + queryParams.value.pageSize;
  dataSource.value = allDataList.value.slice(startIndex, endIndex);
};

/** 搜索按钮操作 */
const handleSearch = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const handleReset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    region: undefined,
    grade: undefined,
    brand: undefined,
    category: undefined,
    productName: undefined
  };
  productList.value = [];
  handleSearch();
};

/** 分页变化 */
const handlePageChange = (page: number) => {
  queryParams.value.pageNum = page;
  updateTableList();
};

/** 分页大小变化 */
const handlePageSizeChange = (_current: number, size: number) => {
  queryParams.value.pageSize = size;
  queryParams.value.pageNum = 1;
  updateTableList();
};

const handleExport = async () => {
  try {
    await exportSalesData(queryParams.value);
    message.success('导出成功');
  } catch (error) {
    message.error('导出失败');
  }
};

const handleBack = () => {
  router.back();
};

onMounted(() => {
  loadOptions();
  getList();
});
</script>

<style scoped>
.sales-data-page {
  padding: 20px;
  background: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #fff;
  margin-bottom: 16px;
  border-radius: 4px;
}

.page-header h2 {
  margin: 0;
  color: #1890ff;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.search-card {
  margin-bottom: 16px;
}

.table-card {
  margin-bottom: 16px;
}
</style>

